/* ************************************************************************
> File Name:     url.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年04月28日 星期四 10时32分17秒
> Description:   
 ************************************************************************/
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include"url.h"

void splice_url(url **ppu, char *str) /*在函数内分配内存得到url的指针，要将此指针传除去必须传入其指针*/
{
    char *saveptr1;
    const char *delim = "?";
    char *path = strtok_r(str, delim, &saveptr1);
    char *key_value = strtok_r(NULL, delim, &saveptr1);

    char *saveptr2, *saveptr3;
    delim = "&";

    *ppu = (url *)malloc(sizeof(url));
    (*ppu)->path = path;

    char *tmp = key_value;
    char *ret;
    int i = 0;
    while (ret = strtok_r(tmp, delim, &saveptr2)){
        tmp = NULL;
        ((*ppu)->p)[i].key = strtok_r(ret, "=", &saveptr3);     
        ((*ppu)->p)[i].value = strtok_r(NULL, "=", &saveptr3);     
        ++i;
    }
    (*ppu)->p_len = i;
}

void print_url(const url *pu){
    printf("Path: %s\n", pu->path); 

    int i;
    for (i = 0; i < pu->p_len; ++i){
        printf("Key: %s\n", (pu->p)[i].key);
        printf("value: %s\n", (pu->p)[i].value);
    }
}

void free_url(url *pu)
{
    free(pu);
    pu = NULL;
}
